<template>
  <div>
    <div ref="mapChina" :class="className" :style="{height:height,width:width}" />
  </div>
</template>
<script>
import echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "@/views/mixins/resize";
require("echarts/map/js/china.js");

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart"
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "460px"
    },
    chinaMapData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null
    };
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.initChart()
    // })
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.mapChina, "macarons");
      // 全国省份数据
      // var toolTipData = this.chinaMapData
      var seriesData = this.chinaMapData;
      // var seriesData = []
      // for (var i = 0; i < toolTipData.length; i++) {
      //   seriesData[i] = {}
      //   seriesData[i].name = toolTipData[i].provinceName
      //   seriesData[i].value = toolTipData[i].shopCount
      //   seriesData[i].provinceKey = toolTipData[i].provinceKey
      // }
      var max = 0;
      if (seriesData.length) {
        max = Math.max.apply(
          Math,
          seriesData.map(function(o) {
            return o.value;
          })
        );
      }
      var min = 0; // 侧边最大值最小值
      var maxSize4Pin = 40,
        minSize4Pin = 30;

      function getGeoCoordMap(name) {
        name = name || "china";
        /* 获取地图数据*/
        var geoCoordMap = {};
        // this.chart.showLoading(); // loading start
        var mapFeatures = echarts.getMap(name).geoJson.features;
        // this.chart.hideLoading(); // loading end
        mapFeatures.forEach(function(v) {
          var name = v.properties.name; // 地区名称
          geoCoordMap[name] = v.properties.cp; // 地区经纬度
        });
        return geoCoordMap;
      }

      function convertData(data) {
        // 转换数据
        var geoCoordMap = getGeoCoordMap("china");
        var res = [];
        for (var i = 0; i < data.length; i++) {
          var geoCoord = geoCoordMap[data[i].name]; // 数据的名字对应的经纬度
          if (geoCoord) {
            // 如果数据data对应上
            res.push({
              name: data[i].name,
              value: geoCoord.concat(data[i].value)
            });
          }
        }
        return res;
      }
      this.chart.setOption({
        tooltip: {
          trigger: "item",
          formatter: function(params) {
            // 鼠标滑过显示的数据
            var toolTiphtml = "";
            if (params && params.value) {
              for (var i = 0; i < seriesData.length; i++) {
                if (params.name === seriesData[i].name) {
                  if(params.value.length == 3){
                     toolTiphtml +=
                    params.name +
                    "：" +
                    params.value[2] +
                    "（" +
                    seriesData[i].ratio +
                    "%）";
                  } else {
                    toolTiphtml +=
                      params.name +
                      "：" +
                      params.value +
                      "（" +
                      seriesData[i].ratio +
                      "%）";
                  }
                }
              }
            } else {
              return params.name;
            }
            return toolTiphtml;
          }
        },
        visualMap: {
          // 视觉映射组件
          show: true,
          min: min,
          max: max, // 侧边滑动的最大值，从数据中获取
          left: "2%",
          inverse: false, // 是否反转 visualMap 组件
          itemWidth: 16, // 图形的宽度，即长条的宽度
          itemHeight: 120, // 图形的高度，即长条的高度
          // text: ['高', '低'], // 文本，默认为数值文本
          calculable: false, // 是否显示拖拽用的手柄（手柄能拖拽调整选中范围）
          seriesIndex: 1, // 指定取哪个系列的数据，即哪个系列的 series.data,默认取所有系列
          orient: "vertical", // horizontal
          inRange: {
            color: ['#dbfefe', '#1066d5'] // 蓝绿
          }
        },
        geo: {
          show: true,
          map: "china",
          roam: false,
          left: "center",
          label: {
            normal: {
              show: false
            },
            emphasis: {
              show: false
            }
          },
          itemStyle: {
            normal: {
              areaColor: "#3c8dbc", // 没有值得时候颜色
              borderColor: "#097bba"
            },
            emphasis: {
              areaColor: "#fbd456" // 鼠标滑过选中的颜色
            }
          }
        },
        series: [
          {
            name: '散点',
            type: "scatter",
            coordinateSystem: "geo",
            data: seriesData,
            symbolSize: 0,
            left: "center",
            label: {
              normal: {
                show: false,
                formatter: "{b}",
                position: "right"
              },
              emphasis: {
                show: true
              }
            },
            itemStyle: {
              normal: {
                // show: false,
                color: "#895139" // 字体颜色
              }
            }
          },
          {
            name: "china",
            type: "map",
            mapType: "china",
            roam: false, // 是否开启鼠标缩放和平移漫游
            data: seriesData,
            left: "center", // 组件距离容器的距离
            // geoIndex: 0,
            // aspectScale: 0.75,       // 长宽比
            // showLegendSymbol: false, // 存在legend时显示
            // selectedMode: 'single', // 选中不高亮
            label: {
              normal: {
                show: true, // 显示省份标签
                textStyle: { // 省份标签字体颜色
                  color: '#895139'
                }
              },
              emphasis: {
                show: true, // 对应的鼠标悬浮效果
                textStyle: {
                  color: "#895139"
                }
              }
            },
            itemStyle: {
              normal: {
                borderWidth: 0.5, // 区域边框宽度
                borderColor: "#0550c3", // 区域边框颜色
                areaColor: "#0b7e9e" // 区域颜色
              },
              emphasis: {
                borderWidth: 0.5,
                borderColor: "#4b0082",
                areaColor: "#ece39e"
              }
            }
          },
          {
            name: "点",
            type: "scatter",
            coordinateSystem: "geo",
            symbol: "pin", // 气泡
            symbolSize: function(val) {
              var a = (maxSize4Pin - minSize4Pin) / (max - min);
              var b = minSize4Pin - a * min;
              b = maxSize4Pin - a * max;
              return a * val[2] + b;
            },
            label: {
              normal: {
                show: true,
                formatter: function(params) {
                  return params.data.value[2];
                },
                textStyle: {
                  color: "#fff",
                  fontSize: 9
                }
              }
            },
            itemStyle: {
              normal: {
                color: "red" //标志颜色'#F62157'
              }
            },
            zlevel: 6,
            data: convertData(seriesData)
          }
        ]
      });
    }
  }
};
</script>
